package cn.lucky.springcloud.controller;

import cn.lucky.springcloud.entities.CommonResult;
import cn.lucky.springcloud.entities.Payment;
import cn.lucky.springcloud.service.PaymentService;
import cn.lucky.springcloud.service.impl.PaymentServiceImpl;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author lingpeng.jiang
 * @create 2020-11-30-23:46
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPost;

    @PostMapping("/payment/create")
    public CommonResult<Integer> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        if (result > 0){
            log.info("插入数据到数据库成功");
            return new CommonResult<>(200,"插入数据库成功",result);
        } else {
            log.info("插入数据到数据库失败");
            return new CommonResult<>(444,"插入失败",null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null){
            log.info("查询成功");
            return new CommonResult<>(200,"查询成功,serverPort:" + serverPost,payment);
        } else {
            log.info("查询失败");
            return new CommonResult<>(444,"查询失败,ID为" + id,null);
        }
    }


    @GetMapping("/payment/list")
    public CommonResult<Payment> queryPayment(){
        List<Payment> payments = paymentService.queryPayment();
        if (payments != null){
            log.info("查询成功");
            return new CommonResult<>(200,"查询成功,serverPort:" + serverPost,payments.get(0));
        } else {
            log.info("查询失败");
            return new CommonResult<>(444,"查询失败",null);
        }
    }


    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services){
            log.info("********element: " + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances){
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    /**
     * 测试自定义负载策略算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String consumerBalancerRule(){
        return serverPost;
    }
}
